use std::sync::mpsc::channel;
use std::thread;
use std::time::Duration;

pub fn send_rece_demo() {
    let (tx, rx) = channel();
    thread::spawn(move || {
        tx.send("hi").unwrap();
    });
    println!("{:?}", rx.recv().unwrap());
}

pub fn use_loop() {
    let (tx, rx) = channel();

    thread::spawn(move || {
        tx.send("hi loop").unwrap();
    });
    //一般try_recv会被用在当线程还有别的事情要处理的时候,
    //这时就可以循环调用try_recv,一边等待数据一边处理别的事情。
    loop {
        match rx.try_recv() {
            Ok(r) => {
                println!("Got: {}", r);
                break;
            }
            Err(e) => {
                println!("i had received empty value");
            }
        }
    }
}
pub fn  use_channel(){
    let (tx, rx) = channel();
    thread::spawn(move || {
        let vals = vec![
            String::from("hi"),
            String::from("from"),
            String::from("the"),
            String::from("thread"),
        ];

        for val in vals {
            tx.send(val).unwrap();
            thread::sleep(Duration::from_secs(1));
        }
    });

    for received in rx {
        println!("Got: {}", received);
    }
}